package com.xxbb.springbootapi.controller;

import com.xxbb.springbootapi.config.WebConfig;
import com.xxbb.springbootapi.entity.JsonResultData;
import com.xxbb.springbootapi.service.impl.SiteOperatorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@Slf4j
@RequestMapping("file")
@Api(tags = "文件操作")
@RestController
public class FileController {

    @Autowired
    private WebConfig webConfig;
    @Autowired
    private SiteOperatorService siteOperatorService;

    @PostMapping("upload")
    @ResponseBody
    @ApiOperation(value = "文件上传至服务器")
    public Object upload(MultipartFile file, HttpServletRequest request, String[] dir) throws IOException {
        //通过路径数组合成路径
        String pt = "";
        for (String item : dir) {
            if (!item.isEmpty()) pt += "/" + item;
        }
        String uploadPath = webConfig.getUploadPath() + "\\ExcelImport";
        File f = new File(uploadPath);
        if (!f.exists()) {
            f.mkdirs();
        }
        log.info(pt);
        //获取upload的绝对路径
        String realPath = webConfig.getUploadPath() + pt;
        //处理文件
        file.transferTo(new File(realPath, file.getOriginalFilename()));
        return new JsonResultData<>(0, "上传成功！", true, file.getOriginalFilename());
    }
    @GetMapping("download")
    @ApiOperation(value = "从服务器下载文件")
    @ResponseBody
    public Object download(HttpServletRequest request, HttpServletResponse response, String fileName) throws IOException {
        //获取相对路径
        String realPath = webConfig.getUploadPath();
        //判断是否是文件
        if (!new File(realPath + fileName).isFile()) {
            return new JsonResultData<>(0, "暂不支持下载文件夹或者当前文件不存在！请勿进行修改代码操作，已记录您本次请求！", true, null);
        }
        //获取文件名
        FileInputStream fileInputStream = new FileInputStream(realPath + fileName);
        //设置响应头
        response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        //流下载
        IOUtils.copy(fileInputStream, outputStream);
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(outputStream);
        log.info(siteOperatorService.getOperator().getName() + "下载文件" + fileName);
        return new JsonResultData<>(1, "请求成功！", true, null);
    }
}
